package com.zhu.esyblog.Utils;

import com.alibaba.fastjson.JSON;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;


@Component
public class QIniuUtils {
    @Value("${qiniu.accessKey}")
     private String accessKey;
    @Value("${qiniu.secretKey}")
    private String secretKey;
    private String bucket="esyblog";
    //构造一个带指定 Region 对象的配置类

    public Boolean upload(MultipartFile file,String fileName) {
        Configuration cfg = new Configuration(Region.region0());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证，然后准备上传
        try {
            byte[] uploadBytes = file.getBytes();
            Auth auth = Auth.create(accessKey, secretKey);
            String uploadToken = auth.uploadToken(bucket);
            Response response = uploadManager.put(uploadBytes, fileName, uploadToken);
            DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    }


